package com.ax.base.system.shiro;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import com.ax.base.common.utils.HttpContextUtils;
import com.ax.base.common.utils.ShiroUtils;
import com.ax.base.system.dao.UserMapper;
import com.ax.base.system.domain.SysUserDO;
import com.ax.base.system.service.MenuService;
import com.google.gson.Gson;

@Repository
public class UserRealm extends AuthorizingRealm {
	@Autowired
	UserMapper userMapper;
	@Autowired
	MenuService menuService;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		return null;
		/*Long userId = ShiroUtils.getUserId();
		Set<String> perms = menuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;*/
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Map<String, Object> map  = new HashMap<>();
		map.put("username", username);
		String password = new String((char[]) token.getCredentials());
		// 查询用户信息
		SysUserDO user = userMapper.list(map).get(0);
		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}
		// 密码错误
		if (!password.equals(user.getPassword())) {
			throw new IncorrectCredentialsException("账号或密码不正确");
		}
		// 账号锁定
		if (user.getStatus() == 0) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		Object sessionId = request.getSession().getAttribute("sessionId");
		if (sessionId == null) {
		sessionId = request.getSession().getId();
		request.getSession().setAttribute("sessionId",sessionId);
		Gson gson = new Gson();
		redisTemplate.opsForValue().set(sessionId.toString(), gson.toJson(user),1800L,TimeUnit.MINUTES);
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
		return info;
	}

}
